package com.lovezy.platform.core.mybatis;

import com.lovezy.platform.core.base.enums.TrueOrFalseEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by jin on 2017/12/6.
 */
@MappedJdbcTypes({JdbcType.TINYINT})
@MappedTypes({Boolean.class})
public class BooleanTypeHandler extends BaseTypeHandler<Boolean> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        preparedStatement.setByte(i, aBoolean ? TrueOrFalseEnum.TRUE.value() : TrueOrFalseEnum.FALSE.value());
    }

    @Override
    public Boolean getNullableResult(ResultSet resultSet, String s) throws SQLException {
        byte aByte = resultSet.getByte(s);
        return aByte == TrueOrFalseEnum.TRUE.value();
    }

    @Override
    public Boolean getNullableResult(ResultSet resultSet, int i) throws SQLException {
        byte aByte = resultSet.getByte(i);
        return aByte == TrueOrFalseEnum.TRUE.value();
    }

    @Override
    public Boolean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        byte aByte = callableStatement.getByte(i);
        return aByte == TrueOrFalseEnum.TRUE.value();
    }

}
